package ink.xiaobaibai.service.impl;

import ink.xiaobaibai.common.Constants;
import ink.xiaobaibai.common.GeneralVerificationCode;
import ink.xiaobaibai.common.ImageVerificationCode;
import ink.xiaobaibai.service.ICodeSendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @description: 图形验证码生成类
 * @author: 小白白
 * @create: 2021-05-15
 **/

@Service
public class ImageCreateServiceImpl implements ICodeSendService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public GeneralVerificationCode createCode(HttpServletRequest request) {

        String key = request.getParameter("uuid");

        ImageVerificationCode imageVerificationCode;
        if (request.getParameter("w") != null && request.getParameter("h") != null) {
            //NumberFormatException
            int w = Integer.parseInt(request.getParameter("w"));
            int h = Integer.parseInt(request.getParameter("h"));
            imageVerificationCode = new ImageVerificationCode(w, h);
        } else {
            imageVerificationCode = new ImageVerificationCode();
        }

        this.stringRedisTemplate.opsForValue().set(Constants.REDIS_KEY_VERIFICATION_CODE + key, imageVerificationCode.getCode(), 180, TimeUnit.SECONDS);

        return imageVerificationCode;
    }

}
